﻿///***************************************************************
/// 시  스  템 : Updms.Fit
/// 단위시스템 : FIT
/// 계      층 : Presentation Layer
/// 프로그램명 : Fit2011r
/// 파  일  명 : Fit2011r.aspx.cs
/// 설      명 : 트레이닝캘린더
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2014-05-29 송시명   최초 작성
///***************************************************************
using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Com.Exe;
using Updms.Fit.Exe;

namespace Updms.Fit
{
	public partial class Fit2011r : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		public static readonly string PID = "Fit2011r";
		public static readonly string gs_path_info = "/updms/Fit/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Com com = new CommCode.Com(LANG_SET);
		CommCode.Etc etc = new CommCode.Etc(LANG_SET);
		CommCode.Fit fit = new CommCode.Fit(LANG_SET);

		//검색
		protected string kw1 = "";	//기준년도
		protected string kw2 = "";	//운동부위
		protected string kw3 = "";	//운동명

		//메뉴 선택값
		protected string gs_sm = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SetEnabledMonthBtn();
				SearchProcess();
			}
			SetClientScriptNoPostBack();
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetSearchDiv();
			SetClientScript();
			SetBaseYm();
			SetSearchTrainingPart();
			SetSearchTrainingType();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript, SetClientScriptNoPostBack

		private void SetClientScript()
		{
		}

		//포스트백과 무관하게 이벤트 지정
		private void SetClientScriptNoPostBack()
		{
			cbl_search_training_part.Items[0].Attributes.Add("onclick", "checkBoxListCheck('cbl_search_training_part');");
			cbl_search_training_type.Items[0].Attributes.Add("onclick", "checkBoxListCheck('cbl_search_training_type');");
		}

		#endregion

		#region SetInit, SetSearchParameter

		//초기값설정
		private void SetInit()
		{
			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			kw1 = ddl_search_base_year.SelectedValue + "-" + ddl_search_base_month.SelectedValue;
			kw2 = WebControlUtil.GetCheckBoxListValue(cbl_search_training_part, 1);
			kw3 = WebControlUtil.GetCheckBoxListValue(cbl_search_training_type, 1);
		}

		#endregion

		#region 마스터 Method (SetBaseYm, SetSearchTrainingPart, SetSearchTrainingType, SetSearchDiv)

		//기준년월 설정
		private void SetBaseYm()
		{
			int li_curr_year = Convert.ToInt32(DateUtil.GetYearEx(0, "yyyy"));

			for (int i = 2014; i <= li_curr_year; i++)
			{
				string ls_year = i.ToString();
				ddl_search_base_year.Items.Add(new ListItem(ls_year, ls_year));
			}

			//기본값
			ddl_search_base_year.SelectedValue = DateUtil.GetYearEx(0, "yyyy");
			ddl_search_base_month.SelectedValue = DateUtil.GetMonthEx(0, "MM");
		}

		//운동부위
		private void SetSearchTrainingPart()
		{
			fit.SetTrainingPart(cbl_search_training_part);

			cbl_search_training_part.Items.Insert(0, new ListItem(GetXmlMsg("STR_019"), "ALL"));	//전체선택
		}

		//운동명
		private void SetSearchTrainingType()
		{
			DataSet lo_ds = new DataSet();
			Fit1010m_NT _Fit1010m_NT = new Fit1010m_NT();

			lo_ds.Merge(_Fit1010m_NT.GetTrainingType());

			cbl_search_training_type.Items.Clear();
			cbl_search_training_type.DataSource = lo_ds;
			cbl_search_training_type.DataMember = "UPDMS_FIT_TRAINING_TYPE";
			cbl_search_training_type.DataTextField = "Training_Nm";
			cbl_search_training_type.DataValueField = "Training_Type_Id";
			cbl_search_training_type.DataBind();

			cbl_search_training_type.Items.Insert(0, new ListItem(GetXmlMsg("STR_019"), "ALL"));	//전체선택
		}

		//조회방법
		private void SetSearchDiv()
		{
			fit.SetSearchDiv(rbl_search_type);
		}

		#endregion

		#region 디테일 Method (SetPrevNextMonth, SetEnabledMonthBtn, SetThisMonth)

		//이전달, 다음달버튼 누르면
		private void SetPrevNextMonth(int pi_month_cnt)
		{
			string ls_ym = ddl_search_base_year.SelectedValue + "-" + ddl_search_base_month.SelectedValue;
			string ls_calc_ym = DateUtil.GetCalcMonth(ls_ym, pi_month_cnt, "yyyy-MM");

			if (WebControlUtil.CheckDdlValue(ddl_search_base_year, ls_calc_ym.Substring(0, 4).ToString()))
			{
				ddl_search_base_year.SelectedValue = ls_calc_ym.Substring(0, 4).ToString();
				ddl_search_base_month.SelectedValue = ls_calc_ym.Substring(5, 2).ToString();
			}

			//버튼처리
			SetEnabledMonthBtn();
		}

		//이전달, 다음달버튼 처리
		private void SetEnabledMonthBtn()
		{
			ibtn_prev_month.Enabled
				= (ddl_search_base_year.SelectedIndex == 0 && ddl_search_base_month.SelectedIndex == 0) ? false : true;

			ibtn_next_month.Enabled
				= (ddl_search_base_year.SelectedIndex == ddl_search_base_year.Items.Count - 1 && ddl_search_base_month.SelectedIndex == 11) ? false : true;
		}

		//당월설정
		private void SetThisMonth()
		{
			string ls_this_ym = DateUtil.GetNow("yyyy-MM");
			ddl_search_base_year.SelectedValue = ls_this_ym.Substring(0, 4).ToString();
			ddl_search_base_month.SelectedValue = ls_this_ym.Substring(5, 2).ToString();
			SetEnabledMonthBtn();
		}

		#endregion

		#region 디테일 Method (GetMonthlyTrainingResult, DrawChartTotalWeightCountByTrainingPart, GetMonthlyTrainingDay)

		//캘린더
		private void GetMonthlyTrainingResult(DataSet lo_ds, string dt_name)
		{
			GridView1.DataSource = lo_ds.Tables[dt_name];
			GridView1.DataBind();

			lbl_this_month.Text = DateUtil.ConvertDateMask(kw1, "yyyy-MM", LANG_SET);
		}

		//챠트
		private void DrawChartTotalWeightCountByTrainingPart(DataSet lo_ds, string dt_name)
		{
			//초기화
			chart_total_weight_count_by_training_part.Data.Clear();

			int li_count = DataSetUtil.GetRowCount(lo_ds, dt_name);
			string dataFieldName = (rbl_search_type.SelectedIndex == 0) ? "Total_Weight" : "Total_Count";
			
			ltr_total_weight_or_count.Text = " (" + rbl_search_type.SelectedItem.Text + ")";

			double ld_max_total = 0.0;

			for (int i = 0; i < li_count; i++)
			{
				string ls_label = DataSetUtil.GetFldStr(lo_ds, dt_name, i, "Training_Part_Nm")
				+ "[" + ConversionUtil.AddComma(DataSetUtil.GetFldStr(lo_ds, dt_name, i, dataFieldName)) + "]"
				+ "[" + DataSetUtil.GetFldStr(lo_ds, dt_name, i, "Training_Day") + "]";
				double ld_total = DataSetUtil.GetFldDbl(lo_ds, dt_name, i, dataFieldName);

				chart_total_weight_count_by_training_part.Data[0, i] = ld_total;
				chart_total_weight_count_by_training_part.AxisX.Labels[i] = ls_label;

				if (ld_max_total < ld_total)
				{
					ld_max_total = ld_total;
				}
			}

			double ldStep;
			ldStep = Convert.ToInt32((ld_max_total / 4) / 1000) * 1000; //천단위 절사
			chart_total_weight_count_by_training_part.AxisY.Step = ldStep;
		}

		//운동일수
		private void GetMonthlyTrainingDay(DataSet lo_ds, string dt_name)
		{
			int li_total_training_day = DataSetUtil.GetFldInt(lo_ds, dt_name, "Total_Training_Day");
			int li_total_day = DataSetUtil.GetFldInt(lo_ds, dt_name, "Total_Day");
			double ld_training_time = DataSetUtil.GetFldDbl(lo_ds, dt_name, "Total_Training_Minute");
			double ld_training_day_avg = DataSetUtil.GetFldDbl(lo_ds, dt_name, "Total_Training_Day_Avg");
			double ld_training_time_avg = DataSetUtil.GetFldDbl(lo_ds, dt_name, "Total_Training_Minute_Avg");

			//총운동시간(분)을 시간으로 환산
			double ld_training_hour = Math.Truncate(ld_training_time / 60); //7850 -> 130.8333 -> 130시간
			double ld_training_hour_min = ld_training_time - (ld_training_hour * 60); //7850 - (130 * 60) -> 50분
			
			lbl_training_day.Text = "<b class=\"todo\">" + li_total_training_day.ToString() + "</b> / " + li_total_day.ToString();
			lbl_training_avg_day.Text = ld_training_day_avg.ToString("#,##0.#") + " %";

			lbl_training_time.Text = ld_training_time.ToString("#,##0") + " Min. ( " + ld_training_hour.ToString("#,##0") + " Hour " + ld_training_hour_min.ToString() + " Min. )";
			lbl_training_avg_time.Text = ld_training_time_avg + " Min.";
		}

		#endregion

		#region CRUD (SearchProcess)

		//검색
		private void SearchProcess()
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_base_ym", typeof(string), kw1);
			lo_dp.AddProperty("ls_training_part", typeof(string), kw2);
			lo_dp.AddProperty("ls_training_type_id", typeof(string), kw3);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			//DataTable명 지정
			string[] dt_name = new string[] {	"FIT2011R_CALENDAR",
												"FIT2011R_CHART",
												"FIT2011R_TRAINING_DAY"
											};

			using (Fit2011r_NT _Fit2011r_NT = new Fit2011r_NT())
			{
				lo_ds.Merge(_Fit2011r_NT.GetMonthlyTrainingResult(lo_dp, dt_name));
			}

			GetMonthlyTrainingResult(lo_ds, dt_name[0]);
			DrawChartTotalWeightCountByTrainingPart(lo_ds, dt_name[1]);
			GetMonthlyTrainingDay(lo_ds, dt_name[2]);
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				for (int i = 0; i < e.Row.Cells.Count; i++)
				{
					e.Row.Cells[i].Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
					e.Row.Cells[i].Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);
				}
			}
		}

		#endregion

		#region 버튼이벤트

		//이전달
		protected void ibtn_prev_month_Click(object sender, EventArgs e)
		{
			SetPrevNextMonth(-1);
			SearchProcess();
		}

		//다음달
		protected void ibtn_next_month_Click(object sender, EventArgs e)
		{
			SetPrevNextMonth(1);
			SearchProcess();
		}

		//당월
		protected void ibtn_this_month_Click(object sender, EventArgs e)
		{
			SetThisMonth();
			SearchProcess();
		}

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SetEnabledMonthBtn();
			SearchProcess();
		}

		#endregion
	}
}